package config

import (
	"cm2"
	"cm2/service/log"
	"cm2/util"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"path"
)

// LoadDefaultConfig 加载 workingPath/conf 中的默认配置参数
func LoadDefaultConfig() (map[string]interface{}, error) {
	return LoadConfig("default")
}

// LoadConfig 加载 workingPath/conf 中的指定的配置参数
func LoadConfig(conf string) (map[string]interface{}, error) {
	confRoot := path.Join(util.GetWorkingPath(), cm2.CONFIGROOT)
	confPath := path.Join(confRoot, fmt.Sprintf("%s.json", conf))

	var (
		data []byte
		err  error
	)
	data, err = ioutil.ReadFile(confPath)

	if err != nil {
		log.DefaultLogger().Errorf("reading config file failed: %s", err)
		return nil, err
	}

	v := map[string]interface{}{}
	err = json.Unmarshal(data, &v)

	if err != nil {
		log.DefaultLogger().Errorf("decoding configuration file failed: %s", err)
		return nil, err
	}

	return v, nil
}
